import { useInterval, useRequest } from 'ahooks'
import {
  MouseEvent,
  forwardRef,
  useEffect,
  useImperativeHandle,
  useMemo,
  useRef,
  useState
} from 'react'

import { ModuleTitle, Tb } from '../../../BigScreenBase/ModuleTitle'
import { AssociationData } from '../../../BigScreenBase/interface'
import { generateCountArray } from '../../../BigScreenBase/utils'
import { SwitchAndIntervalRef } from '../../interface'
import DisplayBox from './components/DisplayBox'
import ProgressChart, { ProgressChartRef } from './components/ProgressChart'
import RightSafeGovernTab, {
  RightSafeGovernTabProps
} from './components/RightSafeGovernTab'
import SecurityGovernancePie, {
  SecurityGovernancePieRef
} from './components/SecurityGovernancePie'
import SecurityGovernanceTable from './components/SecurityGovernanceTable'
import {
  SecurityGovernanceRankingResponse,
  ViolationCategoryData,
  ViolationChartDataResponse,
  calculatePages,
  categoryTabList,
  colors,
  extraColors,
  getSecurityGovernanceRankingData,
  getViolationChartData,
  getViolationOrdrCountData,
  rightSafeGovernTabList
} from './data'

import './index.less'

export type RightSafeGovernProps = {
  selectedAssociationItem: AssociationData
}

const REFRESH_PER_MILLISECOND = 30 * 1000

const securityGovernanceTableHeaders = [
  {
    width: 159,
    title: '对象/违规项'
  },
  {
    width: 110,
    title: '工单类别'
  },
  {
    width: 80,
    title: '治理方式'
  },
  {
    width: 80,
    title: '时间'
  }
]

const RightSafeGovern = forwardRef<SwitchAndIntervalRef, RightSafeGovernProps>(
  (props, ref) => {
    const { key: entId } = props.selectedAssociationItem

    const safeGovernDataIntervalRef = useRef<any>()
    // const safeGovernCategoryIntervalRef = useRef<any>()
    const [currentDateType, setCurrentDateType] = useState<string>('m')
    const currentDateTypeRef = useRef<string>('m')
    // const [currentDateTypeIndex, setCurrentDateTypeIndex] = useState<number>(0)
    const currentDateTypeIndexRef = useRef<number>(0)

    const currentCategoryRef = useRef<string>('cffsKvs')
    const [currentCategory, setCurrentCategory] = useState<string>('cffsKvs')
    // const [currentCategoryIndex, setCurrentCategoryIndex] = useState(0)
    const currentCategoryIndexRef = useRef<number>(0)

    const [chartData, setChartData] = useState<ViolationCategoryData[]>([])
    const [violationChartDataCollection, setViolationChartDataCollection] =
      useState<ViolationChartDataResponse>()
    const [securityGovernanceRankingData, setSecurityGovernanceRankingData] =
      useState<SecurityGovernanceRankingResponse[]>([])

    // 治理工单总数
    const [zhiLiSum, setZhiLiSum] = useState<number>(0)
    // const zhiLiSumRef = useRef<number>(0)
    // const [prevZhiLiSum, setPrevZhiLiSum] = useState<number>(0)
    // const prevZhiLiSumRef = useRef<number>(0)
    // const [endZhiLiSum, setEndZhiLiSum] = useState<number>(0)
    // const endZhiLiSumRef = useRef<number>(0)

    // AI治理工单数
    const [aiZhiLiSum, setAiZhiLiSum] = useState<number>(0)
    const aiZhiLiSumRef = useRef<number>(0)
    const [prevAiZhiLiSum, setPrevAiZhiLiSum] = useState<number>(0)
    const prevAiZhiLiSumRef = useRef<number>(0)
    const [endAiZhiLiSum, setEndAiZhiLiSum] = useState<number>(0)
    const endAiZhiLiSumRef = useRef<number>(0)

    //  人工治理工单数
    const [renGongZhiLiSum, setRenGongZhiLiSum] = useState<number>(0)
    const renGongZhiLiSumRef = useRef<number>(0)
    const [prevRenGongZhiLiSum, setPrevRenGongZhiLiSum] = useState<number>(0)
    const prevRenGongZhiLiSumRef = useRef<number>(0)
    const [endRenGongZhiLiSum, setEndRenGongZhiLiSum] = useState<number>(0)
    const endRenGongZhiLiSumRef = useRef<number>(0)

    // timeout
    const zhiLiSumTimeoutIdRef = useRef<any>()
    const aiZhiLiSumTimeoutIdRef = useRef<any>()
    const renGongZhiLiSumTimeoutIdRef = useRef<any>()

    //数据/时间 分组
    const zhiLiSumUpGroupRef = useRef<{
      countGroup: number[]
      timeGroup: number[]
    }>({
      countGroup: [],
      timeGroup: []
    })

    const aiZhiLiSumUpGroupRef = useRef<{
      countGroup: number[]
      timeGroup: number[]
    }>({
      countGroup: [],
      timeGroup: []
    })

    const renGongZhiLiSumUpGroupRef = useRef<{
      countGroup: number[]
      timeGroup: number[]
    }>({
      countGroup: [],
      timeGroup: []
    })

    const zhiLiUpGroupIndexRef = useRef<number>(0)
    const aiZhiLiUpGroupIndexRef = useRef<number>(0)
    const renGongZhiLiUpGroupIndexRef = useRef<number>(0)

    const securityGovernancePieRef = useRef<SecurityGovernancePieRef>(null)
    const progressChartRef = useRef<ProgressChartRef>(null)
    const [timeInterval, setTimeInterval] = useState<number | undefined>(
      REFRESH_PER_MILLISECOND
    )

    // 治理工单总数
    // function _recursionZhiLiSumSetStartEndCount(gorupIndex: number) {
    //   if (gorupIndex > zhiLiSumUpGroupRef.current.countGroup.length - 1) {
    //     if (zhiLiSumTimeoutIdRef.current) {
    //       clearTimeout(zhiLiSumTimeoutIdRef.current)
    //     }
    //     if (endZhiLiSumRef.current !== zhiLiSumRef.current) {
    //       console.error(
    //         `endZhengWuSumRef.current 【${endZhiLiSumRef.current}】!==zhengWuSumRef 【${zhiLiSumRef.current}】`
    //       )
    //     }
    //     return
    //   }
    //   const timeoutTime = Math.max(1, zhiLiSumUpGroupRef.current.timeGroup[gorupIndex] - 1) //CountUp duration需要1s
    //   if (zhiLiSumTimeoutIdRef.current) {
    //     clearTimeout(zhiLiSumTimeoutIdRef.current)
    //   }
    //   zhiLiSumTimeoutIdRef.current = setTimeout(() => {
    //     if (gorupIndex === 0) {
    //       //初始化时是从1开始的，以后每次更新是从0开始的
    //       prevZhiLiSumRef.current = endZhiLiSumRef.current
    //     } else if (gorupIndex > 0) {
    //       prevZhiLiSumRef.current += zhiLiSumUpGroupRef.current.countGroup[gorupIndex - 1]
    //     }
    //     setPrevZhiLiSum(prevZhiLiSumRef.current)

    //     const currEndCount = zhiLiSumUpGroupRef.current.countGroup[gorupIndex] + prevZhiLiSumRef.current
    //     endZhiLiSumRef.current = currEndCount

    //     setEndZhiLiSum(currEndCount)
    //   }, timeoutTime * 1000)
    // }

    // const handleZhiLiCountUpEnd = () => {
    //   zhiLiUpGroupIndexRef.current += 1
    //   _recursionZhiLiSumSetStartEndCount(zhiLiUpGroupIndexRef.current)
    // }

    // AI治理工单数
    function _recursionAiZhiLiSumSetStartEndCount(gorupIndex: number) {
      if (gorupIndex > aiZhiLiSumUpGroupRef.current.countGroup.length - 1) {
        if (aiZhiLiSumTimeoutIdRef.current) {
          clearTimeout(aiZhiLiSumTimeoutIdRef.current)
        }
        if (endAiZhiLiSumRef.current !== aiZhiLiSumRef.current) {
          console.error(
            `endZhengWuSumRef.current 【${endAiZhiLiSumRef.current}】!==zhengWuSumRef 【${aiZhiLiSumRef.current}】`
          )
        }
        return
      }
      const timeoutTime = Math.max(
        1,
        aiZhiLiSumUpGroupRef.current.timeGroup[gorupIndex] - 1
      ) //CountUp duration需要1s
      if (aiZhiLiSumTimeoutIdRef.current) {
        clearTimeout(aiZhiLiSumTimeoutIdRef.current)
      }
      aiZhiLiSumTimeoutIdRef.current = setTimeout(() => {
        if (gorupIndex === 0) {
          //初始化时是从1开始的，以后每次更新是从0开始的
          prevAiZhiLiSumRef.current = endAiZhiLiSumRef.current
        } else if (gorupIndex > 0) {
          prevAiZhiLiSumRef.current +=
            aiZhiLiSumUpGroupRef.current.countGroup[gorupIndex - 1]
        }
        setPrevAiZhiLiSum(prevAiZhiLiSumRef.current)

        const currEndCount =
          aiZhiLiSumUpGroupRef.current.countGroup[gorupIndex] +
          prevAiZhiLiSumRef.current
        endAiZhiLiSumRef.current = currEndCount

        setEndAiZhiLiSum(currEndCount)
      }, timeoutTime * 1000)
    }

    const handleAiZhiLiCountUpEnd = () => {
      aiZhiLiUpGroupIndexRef.current += 1
      _recursionAiZhiLiSumSetStartEndCount(aiZhiLiUpGroupIndexRef.current)
    }

    // 人工治理工单数
    function _recursionRenGongZhiLiSumSetStartEndCount(gorupIndex: number) {
      if (
        gorupIndex >
        renGongZhiLiSumUpGroupRef.current.countGroup.length - 1
      ) {
        if (renGongZhiLiSumTimeoutIdRef.current) {
          clearTimeout(renGongZhiLiSumTimeoutIdRef.current)
        }
        if (endRenGongZhiLiSumRef.current !== renGongZhiLiSumRef.current) {
          console.error(
            `endRenGongZhiLiSumRef.current 【${endRenGongZhiLiSumRef.current}】!==zhengWuSumRef 【${renGongZhiLiSumRef.current}】`
          )
        }
        return
      }
      const timeoutTime = Math.max(
        1,
        renGongZhiLiSumUpGroupRef.current.timeGroup[gorupIndex] - 1
      ) //CountUp duration需要1s
      if (renGongZhiLiSumTimeoutIdRef.current) {
        clearTimeout(renGongZhiLiSumTimeoutIdRef.current)
      }
      renGongZhiLiSumTimeoutIdRef.current = setTimeout(() => {
        if (gorupIndex === 0) {
          //初始化时是从1开始的，以后每次更新是从0开始的
          prevRenGongZhiLiSumRef.current = endRenGongZhiLiSumRef.current
        } else if (gorupIndex > 0) {
          prevRenGongZhiLiSumRef.current +=
            renGongZhiLiSumUpGroupRef.current.countGroup[gorupIndex - 1]
        }
        setPrevRenGongZhiLiSum(prevRenGongZhiLiSumRef.current)

        const currEndCount =
          renGongZhiLiSumUpGroupRef.current.countGroup[gorupIndex] +
          prevRenGongZhiLiSumRef.current
        endRenGongZhiLiSumRef.current = currEndCount

        setEndRenGongZhiLiSum(currEndCount)
      }, timeoutTime * 1000)
    }

    const handleRenGongZhiLiCountUpEnd = () => {
      renGongZhiLiUpGroupIndexRef.current += 1
      _recursionRenGongZhiLiSumSetStartEndCount(
        renGongZhiLiUpGroupIndexRef.current
      )
    }

    /**
     * 日期类型 - tab 切换事件
     *
     * @param option
     */
    const onTabChange = (option: Tb) => {
      if (currentDateType === option.value) return

      const index = rightSafeGovernTabList.findIndex(
        (item) => item.value === option.value
      )

      setCurrentDateType(option.value as string)

      currentDateTypeRef.current = option.value as string

      currentDateTypeIndexRef.current = index

      const params = { entId, timeType: currentDateTypeRef.current }

      // NOTE: 获取图表数据
      const fetchViolationChartData = () => {
        getViolationChartData(params).then((res) => {
          setViolationChartDataCollection(res)
          setViolationCategoryChartData(currentCategoryRef.current, res)
        })
      }

      // 治理工单总数
      zhiLiSumUpGroupRef.current = {
        countGroup: [],
        timeGroup: []
      }
      zhiLiUpGroupIndexRef.current = 0

      // AI治理工单数
      aiZhiLiSumUpGroupRef.current = {
        countGroup: [],
        timeGroup: []
      }
      aiZhiLiUpGroupIndexRef.current = 0

      // 人工治理工单数
      renGongZhiLiSumUpGroupRef.current = {
        countGroup: [],
        timeGroup: []
      }
      renGongZhiLiUpGroupIndexRef.current = 0
      getViolationOrdrCountData(params).then((res) => {
        if (res) {
          const { allSum = 0, aiSum = 0, rgSum = 0 } = res

          setZhiLiSum(allSum)

          // prevZhiLiSumRef.current = endZhiLiSumRef.current
          // setPrevZhiLiSum(endZhiLiSumRef.current)
          // setEndZhiLiSum(allSum)
          // endZhiLiSumRef.current = allSum

          prevAiZhiLiSumRef.current = endAiZhiLiSumRef.current
          setPrevAiZhiLiSum(endAiZhiLiSumRef.current)
          setEndAiZhiLiSum(aiSum)
          endAiZhiLiSumRef.current = aiSum

          prevRenGongZhiLiSumRef.current = endRenGongZhiLiSumRef.current
          setPrevRenGongZhiLiSum(endRenGongZhiLiSumRef.current)
          setEndRenGongZhiLiSum(rgSum)
          endRenGongZhiLiSumRef.current = rgSum
        }
      })

      fetchViolationChartData()
    }

    /**
     * 安全治理分类 - tab 切换事件
     *
     * @param value
     * @param option
     */
    const onRightSafeGovernTabChange: RightSafeGovernTabProps['onChange'] = (
      value
    ) => {
      if (currentCategory === value) return

      const index = categoryTabList.findIndex((item) => item.value === value)

      currentCategoryIndexRef.current = index

      setCurrentCategory(value as string)
      currentCategoryRef.current = value as string

      setViolationCategoryChartData(
        value as string,
        violationChartDataCollection
      )

      setTimeInterval(REFRESH_PER_MILLISECOND)
    }

    useEffect(() => {
      _initialOrSwitchAssociation('inital', entId)

      return () => {
        clearCountUp()
      }
    }, [])

    const setViolationCategoryChartData = (
      type: string,
      dataSource?: ViolationChartDataResponse
    ) => {
      let data: ViolationCategoryData[]

      switch (type) {
        case 'cffsKvs':
          data = dataSource?.cffsKvs ?? []
          break
        case 'cldxKvs':
          data = dataSource?.cldxKvs ?? []
          break
        case 'wgxKvs':
          data = dataSource?.wgxKvs ?? []
          break
        case 'zhililvKvs':
          data = dataSource?.zhililvKvs ?? []
          break
        default:
          data = []
          break
      }

      setChartData(data)
    }

    function _intervalRefresh() {
      clearCountUp()

      setTimeInterval(REFRESH_PER_MILLISECOND)
      startSafeGovernInterval()

      const params = { entId, timeType: currentDateType }

      // NOTE: 获取图表数据
      const fetchViolationChartData = () => {
        getViolationChartData(params).then((res) => {
          setViolationChartDataCollection(res)
          setViolationCategoryChartData(currentCategoryRef.current, res)
        })
      }

      // NOTE: 获取治理工单数量总览数据
      const fetchViolationOrdrCountData = () => {
        getViolationOrdrCountData(params).then((res) => {
          if (res) {
            const { allSum = 0, aiSum = 0, rgSum = 0 } = res

            setZhiLiSum(allSum)
            // zhiLiSumRef.current = allSum

            setAiZhiLiSum(aiSum)
            aiZhiLiSumRef.current = aiSum

            setRenGongZhiLiSum(rgSum)
            renGongZhiLiSumRef.current = rgSum

            // const zhiLiSumDiff = allSum - endZhiLiSumRef.current
            // if (zhiLiSumDiff === 0) {
            //   return
            // } else {
            //   zhiLiUpGroupIndexRef.current = 0
            //   zhiLiSumUpGroupRef.current = generateCountArray(endZhiLiSumRef.current, allSum)
            //   if (zhiLiSumDiff < 0) {
            //     zhiLiSumUpGroupRef.current = {
            //       countGroup: zhiLiSumUpGroupRef.current.countGroup.map((count) => count * -1),
            //       timeGroup: zhiLiSumUpGroupRef.current.timeGroup
            //     }
            //   }
            //   _recursionZhiLiSumSetStartEndCount(zhiLiUpGroupIndexRef.current)
            // }

            const aiZhiLiSumDiff = aiSum - endAiZhiLiSumRef.current
            if (aiZhiLiSumDiff === 0) {
              return
            } else {
              aiZhiLiUpGroupIndexRef.current = 0
              aiZhiLiSumUpGroupRef.current = generateCountArray(
                endAiZhiLiSumRef.current,
                aiSum
              )
              if (aiZhiLiSumDiff < 0) {
                aiZhiLiSumUpGroupRef.current = {
                  countGroup: aiZhiLiSumUpGroupRef.current.countGroup.map(
                    (count) => count * -1
                  ),
                  timeGroup: aiZhiLiSumUpGroupRef.current.timeGroup
                }
              }
              _recursionAiZhiLiSumSetStartEndCount(
                aiZhiLiUpGroupIndexRef.current
              )
            }

            const renGongZhiLiSumDiff = rgSum - endRenGongZhiLiSumRef.current
            if (renGongZhiLiSumDiff === 0) {
              return
            } else {
              renGongZhiLiUpGroupIndexRef.current = 0
              renGongZhiLiSumUpGroupRef.current = generateCountArray(
                endRenGongZhiLiSumRef.current,
                rgSum
              )
              if (renGongZhiLiSumDiff < 0) {
                renGongZhiLiSumUpGroupRef.current = {
                  countGroup: renGongZhiLiSumUpGroupRef.current.countGroup.map(
                    (count) => count * -1
                  ),
                  timeGroup: renGongZhiLiSumUpGroupRef.current.timeGroup
                }
              }
              _recursionRenGongZhiLiSumSetStartEndCount(
                renGongZhiLiUpGroupIndexRef.current
              )
            }
          }
        })
      }

      fetchViolationOrdrCountData()
      fetchViolationChartData()
    }

    function clearCountUp() {
      if (zhiLiUpGroupIndexRef.current) {
        clearTimeout(zhiLiUpGroupIndexRef.current)
      }

      if (aiZhiLiUpGroupIndexRef.current) {
        clearTimeout(aiZhiLiUpGroupIndexRef.current)
      }

      if (renGongZhiLiUpGroupIndexRef.current) {
        clearTimeout(renGongZhiLiUpGroupIndexRef.current)
      }
    }

    /**
     * 初始化/切换协会时 - 获取数据
     *
     * @param type
     * @param associationKey
     */
    function _initialOrSwitchAssociation(
      type: 'inital' | 'switchAssociation',
      associationKey: string
    ) {
      startSafeGovernInterval()

      // 切换协会
      if (type === 'switchAssociation') {
        clearCountUp()

        setCurrentCategory('cffsKvs')
        currentCategoryRef.current = 'cffsKvs'
        currentCategoryIndexRef.current = 0

        setTimeInterval(REFRESH_PER_MILLISECOND)

        setCurrentDateType('m')
        currentDateTypeRef.current = 'm'
        currentDateTypeIndexRef.current = 0

        // 治理工单总数
        setZhiLiSum(0)
        // zhiLiSumRef.current = 0
        // setPrevZhiLiSum(0)
        // prevZhiLiSumRef.current = 0
        // setEndZhiLiSum(0)
        // endZhiLiSumRef.current = 0

        // AI治理工单数
        setAiZhiLiSum(0)
        aiZhiLiSumRef.current = 0
        setPrevAiZhiLiSum(0)
        prevAiZhiLiSumRef.current = 0
        setEndAiZhiLiSum(0)
        endAiZhiLiSumRef.current = 0

        // 人工治理工单数
        setRenGongZhiLiSum(0)
        renGongZhiLiSumRef.current = 0
        setPrevRenGongZhiLiSum(0)
        prevRenGongZhiLiSumRef.current = 0
        setEndRenGongZhiLiSum(0)
        endRenGongZhiLiSumRef.current = 0

        //数据/时间 分组
        zhiLiSumUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }

        aiZhiLiSumUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }

        renGongZhiLiSumUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }

        zhiLiUpGroupIndexRef.current = 0
        aiZhiLiUpGroupIndexRef.current = 0
        renGongZhiLiUpGroupIndexRef.current = 0
      }

      const params = { entId: associationKey, timeType: currentDateType }

      // NOTE: 获取图表数据
      const fetchViolationChartData = () => {
        getViolationChartData(params).then((res) => {
          setViolationChartDataCollection(res)
          setViolationCategoryChartData(currentCategoryRef.current, res)
        })
      }

      // NOTE: 获取治理工单数量总览数据
      getViolationOrdrCountData(params)
        .then((data) => {
          if (data) {
            const { allSum = 0, aiSum = 0, rgSum = 0 } = data

            setZhiLiSum(allSum)
            // zhiLiSumRef.current = allSum

            setAiZhiLiSum(aiSum)
            aiZhiLiSumRef.current = aiSum

            setRenGongZhiLiSum(rgSum)
            renGongZhiLiSumRef.current = rgSum

            // if (allSum > 0) {
            //   endZhiLiSumRef.current = allSum
            //   setEndZhiLiSum(allSum)
            // }

            if (aiSum > 0) {
              endAiZhiLiSumRef.current = aiSum
              setEndAiZhiLiSum(aiSum)
            }

            if (rgSum > 0) {
              endRenGongZhiLiSumRef.current = rgSum
              setEndRenGongZhiLiSum(rgSum)
            }
          }
        })
        .catch((err: any) => {
          console.error(
            '--OverviewBox--_initialOrSwitchAssociation--postOverviewData--err--:',
            err
          )
        })

      fetchViolationChartData()
    }

    useImperativeHandle(ref, () => ({
      switchAssociation: (newAssociationId: string) => {
        _initialOrSwitchAssociation('switchAssociation', newAssociationId)
      },
      intervalRefresh: _intervalRefresh,
      resize: () => {
        if (securityGovernancePieRef.current) {
          securityGovernancePieRef.current.resize()
        }

        if (progressChartRef.current) {
          progressChartRef.current.resize?.()
        }
      }
    }))

    /**
     * 安全治理分类 - tab切换定时器
     */
    useInterval(() => {
      const newIndex =
        (currentCategoryIndexRef.current + 1) % categoryTabList.length
      const newValue = categoryTabList[newIndex].value

      setCurrentCategory(newValue as string)
      currentCategoryRef.current = newValue as string

      currentCategoryIndexRef.current = newIndex

      setViolationCategoryChartData(
        newValue as string,
        violationChartDataCollection
      )
    }, timeInterval)

    /**
     * 安全治理面板数据 - 清除自动切换日期tab的定时器
     */
    function clearSafeGovernDataInterval() {
      if (safeGovernDataIntervalRef.current) {
        clearInterval(safeGovernDataIntervalRef.current)
        safeGovernDataIntervalRef.current = undefined
      }
    }

    const prevZhiLiSum = useMemo(
      () => prevAiZhiLiSum + prevRenGongZhiLiSum,
      [prevAiZhiLiSum, prevRenGongZhiLiSum]
    )
    const endZhiLiSum = useMemo(
      () => endAiZhiLiSum + endRenGongZhiLiSum,
      [endAiZhiLiSum, endRenGongZhiLiSum]
    )

    /**
     * 安全治理面板数据 - 开启自动切换日期tab定时器
     */
    function startSafeGovernInterval() {
      clearSafeGovernDataInterval()

      safeGovernDataIntervalRef.current = setInterval(() => {
        const newIndex =
          (currentDateTypeIndexRef.current + 1) % rightSafeGovernTabList.length

        currentDateTypeIndexRef.current = newIndex

        const newValue = rightSafeGovernTabList[newIndex].value

        setCurrentDateType(newValue as string)

        currentDateTypeRef.current = newValue as string

        const params = { entId, timeType: currentDateTypeRef.current }

        // NOTE: 获取图表数据
        const fetchViolationChartData = () => {
          getViolationChartData(params).then((res) => {
            setViolationChartDataCollection(res)
            setViolationCategoryChartData(currentCategoryRef.current, res)
          })
        }

        // 治理工单总数
        zhiLiSumUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }
        zhiLiUpGroupIndexRef.current = 0

        // AI治理工单数
        aiZhiLiSumUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }
        aiZhiLiUpGroupIndexRef.current = 0

        // 人工治理工单数
        renGongZhiLiSumUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }
        renGongZhiLiUpGroupIndexRef.current = 0
        // NOTE: 获取治理工单数量总览数据
        getViolationOrdrCountData(params).then((res) => {
          if (res) {
            const { allSum = 0, aiSum = 0, rgSum = 0 } = res

            setZhiLiSum(allSum)
            // prevZhiLiSumRef.current = endZhiLiSumRef.current
            // setPrevZhiLiSum(endZhiLiSumRef.current)
            // setEndZhiLiSum(allSum)
            // endZhiLiSumRef.current = allSum

            prevAiZhiLiSumRef.current = endAiZhiLiSumRef.current
            setPrevAiZhiLiSum(endAiZhiLiSumRef.current)
            setEndAiZhiLiSum(aiSum)
            endAiZhiLiSumRef.current = aiSum

            prevRenGongZhiLiSumRef.current = endRenGongZhiLiSumRef.current
            setPrevRenGongZhiLiSum(endRenGongZhiLiSumRef.current)
            setEndRenGongZhiLiSum(rgSum)
            endRenGongZhiLiSumRef.current = rgSum
          }
        })

        fetchViolationChartData()
      }, 60 * 1000)
    }

    useRequest(
      () => {
        return getSecurityGovernanceRankingData({ entId, topNum: '8' })
      },
      {
        onSuccess(data) {
          if (data) {
            setSecurityGovernanceRankingData(data)
          }
        },
        refreshDeps: [entId],
        pollingInterval: 10 * 1000
      }
    )

    const onSafeGovernTabMouseEnter = (e: MouseEvent) => {
      setTimeInterval(undefined)
    }

    const onSafeGovernTabMouseLeave = (e: MouseEvent) => {
      setTimeInterval(REFRESH_PER_MILLISECOND)
    }

    return (
      <div
        className="bigscreen-module ms-module right-safe-govern"
        style={{ height: 620 }}
      >
        <ModuleTitle
          title="安全治理"
          tab={rightSafeGovernTabList}
          activeKey={currentDateType}
          tabChange={onTabChange}
          onTitleTabMouseEnter={clearSafeGovernDataInterval}
          onTitleTabMouseLeave={startSafeGovernInterval}
        />
        <div style={{ padding: 16 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <DisplayBox
              label="治理工单总数"
              prevCount={prevZhiLiSum}
              endCount={endZhiLiSum}
            />
            <DisplayBox
              label="AI治理工单数"
              prevCount={prevAiZhiLiSum}
              endCount={endAiZhiLiSum}
              onCountUpEnd={handleAiZhiLiCountUpEnd}
            />
            <DisplayBox
              label="人工治理工单数"
              prevCount={prevRenGongZhiLiSum}
              endCount={endRenGongZhiLiSum}
              onCountUpEnd={handleRenGongZhiLiCountUpEnd}
            />
          </div>
          <div
            className="line-radius"
            style={{ width: 398, padding: '16px 0' }}
          ></div>
          <div className="chart-wrapper">
            <div className="chart-box">
              <RightSafeGovernTab
                options={categoryTabList}
                onChange={onRightSafeGovernTabChange}
                activeTabValue={currentCategory}
                onMouseEnter={onSafeGovernTabMouseEnter}
                onMouseLeave={onSafeGovernTabMouseLeave}
              />
            </div>
            <div style={{ padding: '0 8px' }}>
              {currentCategory === 'zhililvKvs' ? (
                <ProgressChart
                  ref={progressChartRef}
                  chartData={chartData}
                  colors={
                    chartData.length > 0
                      ? Array(calculatePages(chartData.length, 9))
                          .fill(colors)
                          .flat(1)
                      : colors
                  }
                />
              ) : (
                <SecurityGovernancePie
                  ref={securityGovernancePieRef}
                  colors={
                    currentCategory === 'cldxKvs'
                      ? extraColors
                      : chartData.length > 0
                        ? Array(calculatePages(chartData.length, 9))
                            .fill(colors)
                            .flat(1)
                        : colors
                  }
                  chartData={chartData}
                />
              )}
            </div>
          </div>
          <div
            className="line-radius"
            style={{ width: 398, padding: '12px 0' }}
          ></div>
          <div style={{ height: 291, width: '100%' }}>
            <SecurityGovernanceTable
              headers={securityGovernanceTableHeaders}
              dataSourse={securityGovernanceRankingData}
            />
          </div>
        </div>
      </div>
    )
  }
)

export default RightSafeGovern
